//
//  CCScrollLayer.m
//  CandyJump
//
//  Created by Jordy on 11年6月6日.
//  Copyright 2011 Peru Republic. All rights reserved.
//

#import "CCScrollLayer.h"

@implementation CCScrollLayer

-(id) initWithMenuItems:(NSMutableArray *)items
{
	
	if ((self = [super init]))
	{
		[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:YES];
		
		scrollWidth = [[CCDirector sharedDirector] winSize].width;
		scrollHeight = [[CCDirector sharedDirector] winSize].height;
		
		int i = 0;
		for (CCMenuItem *item in items)
		{
			item.anchorPoint = ccp(0,0);
			item.position = ccp(scrollWidth / 2, scrollHeight / 2 - (i * scrollHeight));
			[self addChild:item];
			i++;
		}
		
		currentScreen = 1;
		totalScreens = [items count];
	}
	return self;
}

-(void) move
{
	float dest = ((currentScreen-1) * scrollHeight);
	[self runAction:[CCEaseBounce actionWithAction:[CCMoveTo actionWithDuration:0.2 position:ccp(0, dest)]]];
}

- (void)onExit
{
	[[CCTouchDispatcher sharedDispatcher] removeDelegate:self];
	[super onExit];
}

-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint touchPoint = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
	startPos = touchPoint.y;
	return YES;
}

- (void)ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint touchPoint = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
	self.position = ccp(0, ((currentScreen - 1) * scrollHeight) + (touchPoint.y - startPos));
}

- (void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
{
	CGPoint touchPoint = [[CCDirector sharedDirector] convertToGL:[touch locationInView:[touch view]]];
	
	if ((touchPoint.y - startPos) > 50 && (currentScreen + 1) <= totalScreens)
	{
		currentScreen++;
	}
	else if ((touchPoint.y - startPos) < -50 && (currentScreen - 1) > 0)
	{
		currentScreen--;
	}
	
	[self move];
}

- (void) dealloc
{
	[super dealloc];
}

@end
